package com.duojuhe.websocket.subscriber.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.duojuhe.common.utils.thread.ThreadUtils;
import com.duojuhe.websocket.EventCodes;
import com.duojuhe.websocket.SocketMessage;
import com.duojuhe.websocket.SocketUtil;
import com.duojuhe.websocket.subscriber.message.sendmsg.SystemSendMessageDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

/**
 * @Description 集群系统消息监听器
 * @Date 2020/3/29 15:07
 */
@Slf4j
@Component
public class SystemMessageListener implements MessageListener {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer<String> valueSerializer = stringRedisTemplate.getStringSerializer();
        String messageContent = valueSerializer.deserialize(message.getBody());
        JSONObject jsonObject= JSONObject.parseObject(messageContent);
        //将字符串转成对象
        if (jsonObject==null){
            log.info("【系统消息】监听集群系统 Websocket消息为空---{}",messageContent);
            return;
        }
        log.info("【系统消息】监听集群系统 Websocket消息--- {}", jsonObject);
        //消息事件类型
        String eventType = jsonObject.getString("eventType");
        //消息事件内容
        JSONObject jsonMessageData = jsonObject.getJSONObject("messageData");
        if (jsonMessageData==null){
            log.info("【系统消息】监听集群系统 Websocket消息jsonMessageData不可为空");
            return;
        }
        if (EventCodes.EVENT_SYSTEM_MESSAGE.getEvent().equals(eventType)){
            //系统消息发送
            eventSystemSendMessageHandle(jsonMessageData);
        }
    }



    /**
     * 发送系统未读消息数
     * @param jsonObject
     */
    private void eventSystemSendMessageHandle(JSONObject jsonObject){
        SystemSendMessageDto sendMessageDto = JSON.parseObject(jsonObject.toJSONString() , SystemSendMessageDto.class);
        //接收对象id
        String receiverId = sendMessageDto.getUserId();
        if (StringUtils.isBlank(receiverId)){
            return;
        }
        //给指定用户id通知一份消息
        ThreadUtils.execute(() -> SocketUtil.sendMessageToUserId(receiverId, SocketMessage.eventSystemMessage(sendMessageDto.getMessageUntreatedDto())));
    }
}